package converts

import (
	"gitee.com/captials-team/ubdframe/src/domain/dto"
	"gitee.com/captials-team/ubdframe/src/domain/interfaces"
	"strings"
)

func ConvertTree[T interfaces.ItfTreeNode](nodes []T, assignRoot ...string) []*dto.TreeNode[T] {
	//根节点
	var root = &dto.TreeNode[T]{}
	var m = map[string]*dto.TreeNode[T]{}
	var rootNode = ""
	if len(assignRoot) > 0 {
		rootNode = assignRoot[0]
	}

	newNode := func(node T) *dto.TreeNode[T] {
		return &dto.TreeNode[T]{
			Id:       node.NodeId(),
			Name:     node.NodeName(),
			Pid:      node.NodePid(),
			Children: []*dto.TreeNode[T]{},
			Data:     node,
		}
	}
	for {
		n := 0

		for _, v := range nodes {
			nodeId := v.NodeId()
			pid := v.NodePid()

			if _, exist := m[nodeId]; exist {
				continue
			}

			if pid == rootNode {
				//顶级节点
				node := newNode(v)

				root.Children = append(root.Children, node)
				m[nodeId] = node
				n++
				continue
			}
			if parent, exist := m[pid]; exist {
				//上级节点
				node := newNode(v)

				parent.Children = append(parent.Children, node)
				m[nodeId] = node
				n++
				continue
			}
		}

		//遇到环或已处理完就结束
		if n == 0 {
			break
		}
	}

	if root.Children == nil {
		return []*dto.TreeNode[T]{}
	}

	return root.Children
}

func PrintTree[T interfaces.ItfTreeNode](t log, tree []*dto.TreeNode[T]) {
	_printTree(t, tree, 0)
}

func _printTree[T interfaces.ItfTreeNode](t log, tree []*dto.TreeNode[T], level int) {
	if len(tree) == 0 {
		return
	}
	for _, v := range tree {
		t.Logf("%s%+v", strings.Repeat("\t", level*2), v)
		_printTree(t, v.Children, level+1)
	}
}

type log interface {
	Logf(format string, a ...interface{})
}
